package com.chenjun.core.service.oa.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chenjun.common.Constant;
import com.chenjun.common.bean.Pagination;
import com.chenjun.common.model.DataGridModel;
import com.chenjun.common.model.DataGridSortModel;
import com.chenjun.common.util.DateUtil;
import com.chenjun.core.dao.generator.entity.OaBillOvertimeApplication;
import com.chenjun.core.dao.generator.mapper.OaBillOvertimeApplicationMapper;
import com.chenjun.core.dao.module.OaBillOvertimeApplicationRelationMapper;
import com.chenjun.core.service.oa.OvertimeManagerService;
import com.chenjun.core.vo.activiti.OvertimeStatisticsDto;

@Service
@Transactional
public class OvertimeManagerServiceImpl implements OvertimeManagerService {
	
	@Resource
	private OaBillOvertimeApplicationMapper overTimeMapper;
	
	@Resource
	private OaBillOvertimeApplicationRelationMapper overTimeRelationMapper;

	@Override
	public OaBillOvertimeApplication get(Integer id) {
		return overTimeMapper.selectByPrimaryKey(id);
	}

	@Override
	public int delete(Integer id) {
		return overTimeMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int createOrUpdate(OaBillOvertimeApplication record) {
		int rows = 0;
		if (record.getId() == null) {
			rows = overTimeMapper.insert(record);
		} else {
			rows = overTimeMapper.updateByPrimaryKeySelective(record);
		}
		return rows;
	}

	@Override
	public Pagination doPagination(DataGridModel param) {
		Pagination vo = new Pagination();
		List<OaBillOvertimeApplication> list = overTimeRelationMapper.selectByCondition(param);
		param.setStart(0);
		param.setRows(0);
		int size = overTimeRelationMapper.countByCondition(param);
		vo.setAaData(list);
		vo.setiTotalRecords(size);
		vo.setsEcho(param.getPage());
		vo.setiTotalDisplayRecords(size);
		return vo;
	}

	@Override
	public List<OaBillOvertimeApplication> doListByCondition(DataGridModel param) {
		return overTimeRelationMapper.selectByCondition(param);
	}
	
	/**
	 * 加班统计
	 * @param param
	 * @return
	 * @author dongyibin
	 * @date 2017-9-23 下午4:49:30
	 */
	@Override
	public Pagination getOverTimeStatistics(DataGridModel dataGridModel) {
		Pagination vo = new Pagination();
		// 默认取当月数据
		Calendar currDate = Calendar.getInstance();
		currDate.setTime(new Date());
		int year = currDate.get(Calendar.YEAR);
		int month = currDate.get(Calendar.MONTH) + 1;
		String userids = dataGridModel.getParams().get("userIds").toString();
		String date = dataGridModel.getParams().get("startTime").toString();
		if(!(StringUtils.isBlank(date) || date.equals("null"))){
			String[] dates = date.split("-");
			year = Integer.parseInt(dates[0]);
			month = Integer.parseInt(dates[1]);
		}
		List<OvertimeStatisticsDto> results = new ArrayList<>();
		String[] ids = userids.replaceAll("'", "").split(",");// js处理中加了单引号
		for (String userid : ids) {
			if(StringUtils.isBlank(userid)){
				continue;
			}
			BigDecimal zero = new BigDecimal(0f);
			// 不同日期加班小时数
			BigDecimal thisWeekdayOverHours = new BigDecimal(0f);
			BigDecimal thisWeekendOverHours = new BigDecimal(0f);
			BigDecimal thisHolidayOverHours = new BigDecimal(0f);
			
			BigDecimal allWeekdayOverHours = new BigDecimal(0f);
			BigDecimal allWeekendOverHours = new BigDecimal(0f);
			BigDecimal allHolidayOverHours = new BigDecimal(0f);
			OvertimeStatisticsDto dto = new OvertimeStatisticsDto();
			dto.setStatisticsDate(year + "年" + month + "月");
			int minMonth = 1; // 年度最小月份
			boolean tag = true;
			Map<String, BigDecimal> p = new HashMap<>();
			while(month>= minMonth){
				p.put("weekdayOverHours", zero);
				p.put("weekendOverHours", zero);
				p.put("holidayOverHours", zero);
				BigDecimal weekdayOverHours = new BigDecimal(0f);
				BigDecimal weekendOverHours = new BigDecimal(0f);
				BigDecimal holidayOverHours = new BigDecimal(0f);
				getMonthOverTimeStatistics(year,month,userid,p);
				weekdayOverHours = p.get("weekdayOverHours");
				weekendOverHours = p.get("weekendOverHours");
				holidayOverHours = p.get("holidayOverHours");
				if(tag){
					tag = false;
					thisWeekdayOverHours = weekdayOverHours;
					thisWeekendOverHours = weekendOverHours;
					thisHolidayOverHours = holidayOverHours;
				}
				allWeekdayOverHours = allWeekdayOverHours.add(weekdayOverHours);
				allWeekendOverHours = allWeekendOverHours.add(weekendOverHours);
				allHolidayOverHours = allHolidayOverHours.add(holidayOverHours);
				month--;
			}
			dto.setEmplId(userid);
			dto.setEmplName("---"); // 员工考勤方式设置表未实现
			dto.setHoursTypeName(""); // 员工考勤方式设置表未实现
			dto.setThis_weekday(thisWeekdayOverHours.toString());
			dto.setThis_weekend(thisWeekendOverHours.toString());
			dto.setThis_holiday(thisHolidayOverHours.toString());
			dto.setAll_weekday(allWeekdayOverHours.toString());
			dto.setAll_weekend(allWeekendOverHours.toString());
			dto.setAll_holiday(allHolidayOverHours.toString());
			results.add(dto);
		}
		vo.setAaData(results);
		vo.setiTotalRecords(results.size());
		vo.setsEcho(dataGridModel.getPage());
		vo.setiTotalDisplayRecords(results.size());
		return vo;
		
	}
	
	public void getMonthOverTimeStatistics(int year, int month, String userid,Map<String, BigDecimal> p){
		BigDecimal weekdayOverHours = new BigDecimal(0f);
		BigDecimal weekendOverHours = new BigDecimal(0f);
		BigDecimal holidayOverHours = new BigDecimal(0f);
		// 查询时间区间应包含加班的上下班时间
		DataGridModel param = new DataGridModel();
		param.setRows(0);
		param.getParams().put("year", year);
		param.getParams().put("month", month);
		param.getParams().put("emplId", userid);
		param.getParams().put("status", Constant.APPLY_PASS); // 审核通过
		param.getSortBy().add(new DataGridSortModel("bill_date", DataGridSortModel.ASC));
		List<OaBillOvertimeApplication> overtimeApplications = doListByCondition(param);
		if (overtimeApplications == null || overtimeApplications.isEmpty()) {
			return;
		}
		Calendar calendar = Calendar.getInstance();
		// 不同日期加班小时数
		for (OaBillOvertimeApplication overtimeApplication : overtimeApplications) {
			calendar.setTime(overtimeApplication.getOnDutyTime()); // 设置日期
			long onDutyTime = overtimeApplication.getOnDutyTime().getTime(); // 上班时间
			long offDutyTime = overtimeApplication.getOffDutyTime().getTime(); // 下班时间
			BigDecimal differenceHour = DateUtil.getDifferenceHour(onDutyTime, offDutyTime); // 加班小时数
			if (overtimeApplication.getIsHolidays() == Constant.STATUS_TRUE) { // 节假日
				holidayOverHours = holidayOverHours.add(differenceHour);
				p.put("holidayOverHours", holidayOverHours);
			} else if (DateUtil.isWeekend(calendar)) { // 周日
				weekendOverHours = weekendOverHours.add(differenceHour);
				p.put("weekendOverHours", weekendOverHours);
			} else { // 工作日
				weekdayOverHours = weekdayOverHours.add(differenceHour);
				p.put("weekdayOverHours", weekdayOverHours);
			}
		}
	}

}
